package com.webchat.chat.core.tools;

import com.webchat.chat.core.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Owner on 2018/7/11.
 */
public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * Protect from being instance.
     */
    private FileUtil() {
    }

    public static String uploadFile(MultipartFile file, String rootPath, String tenantCode, String userName){

        if(file == null || StringUtils.isBlank(tenantCode) || StringUtils.isBlank(userName)){
            return null;
        }

        String fileName = file.getOriginalFilename().toLowerCase();
        String contentType = fileName;
        int i = contentType.indexOf(".");
        int leg = contentType.length();
        contentType = (i > 0 ? (i + 1) == leg ? " " : contentType.substring(i, contentType.length()) : " ");
        if(StringUtils.isBlank(fileName)){
            fileName = UUID.randomUUID().toString();
        }
        if(fileName.length() > 5){
            fileName = fileName.substring(0, 5);
        }
        fileName = System.currentTimeMillis() + "_" + fileName + contentType;

        File targetFile = new File(rootPath + tenantCode + File.separator + userName, fileName);
        if(!targetFile.exists()){
            targetFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error("[{}----{}]上传文件[{}]失败。错误信息{}", tenantCode, userName, file.getOriginalFilename(), e.getMessage());
            throw new ServiceException("文件上传失败");
        }

        return targetFile.getAbsolutePath();
    }

}
